/**
 * vue3+vite实现动态加载图片
 * @param name 图片名称（包含后缀名）
 * @returns 图片路径
 */
export const importImage = (name: string) => {
  return new URL(`../assets/images/${name}`, import.meta.url).href;
};

/**
 * 获取图片主要颜色
 * @param image 图片元素
 * @returns 图片主要颜色 rgb(xxx,xxx,xxx)
 */
export const getImageMainColor = (image: HTMLImageElement) => {
  const canvas = document.createElement("canvas");
  const ctx = canvas.getContext("2d");
  if (!ctx) {
    console.error("ctx(即CanvasRenderingContext2D)为空");
    return "rgba(0,0,0,1)";
  }
  canvas.width = image.width;
  canvas.height = image.height;
  ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
  const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  const pixels = imageData.data;
  const colorsMap = new Map();
  let maxCount = 0,
    mainColor = null;
  for (let i = 0; i < pixels.length; i += 4) {
    const offset = i;
    const red = pixels[offset + 0];
    const green = pixels[offset + 1];
    const blue = pixels[offset + 2];
    const alpha = pixels[offset + 3];
    const color = [red, green, blue, alpha].join(",");
    colorsMap.set(color, (colorsMap.get(color) || 0) + 1);
    if (colorsMap.get(color) > maxCount) {
      maxCount = colorsMap.get(color);
      mainColor = color;
    }
  }
  return `rgba(${mainColor})`;
};
